<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>学校数据管理</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('school-add')" @click="addAdminOpen('add',0)">新增</el-button>
          <!-- <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="success" icon="el-icon-edit" :disabled="!checkPermission('administrators-add')" @click="getExcel()">导入Excel</el-button> -->
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-input v-model="query.name" type="text" placeholder="输入学校名称" />
        </el-col>
        <el-col :span="4">
          <el-select v-model.number="query.type" :placeholder="$t('table.selectThe')+'国内外'" style="width: 100%;" clearable @clear="clearCate1">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="550px" style="margin-top: 20px;">
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column label="学校名称" prop="name" />
        <el-table-column label="学校标识码" prop="code" />
        <el-table-column label="办学层次" prop="level">
          <template slot-scope="{row}">
            <el-tag :type="row.level|statusFilter">
              {{ row.level|schoolLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="国内外" prop="type">
          <template slot-scope="{row}">
            {{ row.type|schoolType }}
          </template>
        </el-table-column>
        <el-table-column label="省份" prop="province" />
        <el-table-column label="城市" prop="city" />
        <el-table-column label="学校类型" prop="mechanism">
          <template slot-scope="{row}">
            {{ row.mechanism|mechanism }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('school-edit')" @click="addAdminOpen('edit',row)">{{ $t('button.edit') }}</el-button>

            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('school-del')" @click="delUserAdmin(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" top="40px" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
        <div class="shopOrder-dialog">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+'学校名称'" style="width:50%" />
          </el-form-item>
          <el-form-item label="学校标识码" prop="code">
            <el-input v-model="formData.code" :placeholder="$t('table.enterThe')+'学校标识码'" style="width:50%" />
          </el-form-item>
          <el-form-item label="办学层次">
            <el-radio-group v-model.number="formData.level">
              <el-radio :label="1">专科</el-radio>
              <el-radio :label="2">本科</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="国内外">
            <el-radio-group v-model.number="formData.type">
              <el-radio :label="1">国内</el-radio>
              <el-radio :label="2">国际(含港澳台)</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="formData.type===1" label="选择省份/城市">
            <el-select v-model="formData.province" :placeholder="$t('table.selectThe')+'省份'" style="margin-right: 10px;" @change="provincedata">
              <el-option v-for="(item,index) in provinceList" :key="index" :label="item.fullname" :value="item.fullname" />
            </el-select>
            <el-select v-model="formData.city" :placeholder="$t('table.selectThe')+'城市'" @change="citydata">
              <el-option v-for="(item,index) in city" :key="index" :label="item.fullname" :value="item.fullname" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.type===2" label="国家或港澳台" prop="province">
            <el-input v-model="formData.province" :placeholder="$t('table.enterThe')+'国家或港澳台'" style="width:50%" />
          </el-form-item>
          <el-form-item label="学校类型">
            <el-radio-group v-model.number="formData.mechanism">
              <el-radio :label="0">公立</el-radio>
              <el-radio :label="1">民办</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 导入Excel -->
    <el-dialog title="导入Excel" :visible="showDialogS" top="40px" @close="btnCanleS">
      <div class="shopOrder-dialog">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :http-request="UploadFile"
          :file-list="fileList"
          multiple
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传xlsx,xls文件，且不超过500kb</div>
        </el-upload>

      </div>
    </el-dialog>
  </div>
</template>
<script>
import { GetSchool, SchoolAdd, SchoolDel, ExcelSchool } from '@/api/user'
import user from '@/store/modules/user'
import province from '@/api/m_province'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'primary',
        3: 'warning'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: '国内'
      },
      {
        id: 2,
        value: '国外'
      }],
      query: {
        page: 1,
        limit: 10,
        name: '',
        type: undefined
      },
      count: 0,
      dialogTitle: '新增',
      formData: {
        id: undefined,
        name: '',
        code: '',
        province: '',
        city: '',
        level: 2,
        type: 1,
        mechanism: 1
      },
      rules: {
        name: [{ required: true, message: '学校名称' + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false,
      fullscreenLoading: false,
      showDialogS: false,
      fileList: [],
      provinces: [],
      provinceList: [],
      city: []
    }
  },
  created() {
    // 获取userid
    this.formData.operator_uid = parseFloat(user.state.userId)
    this.getUserAdmin()
    this.getProvince()
  },
  methods: {
    citydata(data) {
      var dataL = []
      var cur = 0
      province.RECORDS.forEach(item => {
        if (item.fullname === data) {
          cur = item.cid
        }
      })
      console.log(cur)
      province.RECORDS.forEach(item => {
        if (item.pid === (cur / 100)) {
          dataL.push(item)
        }
      })
      console.log(dataL)
    },
    // 获取省份
    getProvince() {
      province.RECORDS.forEach(item => {
        if (item.pid === 0) {
          this.provinceList.push(item)
        }
      })
    },
    // 监听下拉
    provincedata(data) {
      var cur = 0
      province.RECORDS.forEach(item => {
        if (item.fullname === data && item.pid === 0) {
          cur = item.cid
        }
      })
      this.city = []
      province.RECORDS.forEach(item => {
        if (item.pid === (cur / 1000)) {
          this.city.push(item)
        }
      })
    },
    // 上传
    async UploadFile(params) {
      const formData = new FormData()// 定义新的formData
      // 为formData赋值
      formData.append('file', params.file)
      // 发起上传请求
      const file = await ExcelSchool(formData)
      // 循环数组，为对应的filelist中的url替换
      this.fileList = this.fileList.map(item => {
        if (item.uid === this.currentFileUid) {
          return { url: file.file, upload: true, name: file.name }
        }
        this.getUserAdmin()
        this.$message.success('成功！')
        return item
      })
    },
    depClick(e) {
      console.log(e)
      this.query.jid = e[e.length - 1]
    },
    getExcel() {
      this.showDialogS = true
    },
    // 获取管理员列表
    async getUserAdmin() {
      this.downloadLoading = true
      const { count, list } = await GetSchool(this.query)
      this.list = list
      this.count = count
      this.downloadLoading = false
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getUserAdmin()
    },
    // 点击展开新增修改
    addAdminOpen(type, row) {
      if (type === 'add') {
        this.dialogTitle = '新增'
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = '修改'
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.province = row.province
        this.formData.city = row.city
        this.formData.code = row.code
        this.formData.level = row.level
        this.formData.type = row.type
        this.formData.mechanism = row.mechanism
        this.provincedata(this.formData.province)
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    clearCate1() {
      this.query.type = undefined
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()

        // 调用新增接口
        await SchoolAdd(this.formData)
        // 更新数据
        this.getUserAdmin()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        id: undefined,
        reason: '',
        type: undefined
      }
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    btnCanleS() {
      this.fileList = []
      this.showDialogS = false
    },
    // 删除管理员
    async delUserAdmin(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await SchoolDel(data)
        this.getUserAdmin()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getUserAdmin()
    }
  }
})
</script>

<style scoped lang="scss">
.table-img{
  width: 80px;
}
.shopOrder-dialog{
  height: auto;
  max-height: 600px;
  overflow-y: auto;
  .editor{
    width: 500px;
  }
}
.shopOrder-dialog::-webkit-scrollbar{display:none}
</style>
